#!/usr/bin/bash

_sdk() {
	local -r previous_word=${COMP_WORDS[COMP_CWORD - 1]}
	local -r current_word=${COMP_WORDS[COMP_CWORD]}

	if ((COMP_CWORD == 3)); then
		local -r before_previous_word=${COMP_WORDS[COMP_CWORD - 2]}

		__sdkman_complete_candidate_version "$before_previous_word" "$previous_word" "$current_word"

		return
	fi

	__sdkman_complete_command "$previous_word" "$current_word"
}

__sdkman_complete_command() {
	local -r command=$1
	local -r current_word=$2

	local -a candidates

	case $command in
		sdk)
			candidates=("install" "uninstall" "list" "use" "config" "default" "home" "env" "current" "upgrade" "version" "help" "offline" "selfupdate" "update" "flush")
			;;
		current|c|default|d|home|h|uninstall|rm|upgrade|ug|use|u)
			local -r candidate_paths=("${SDKMAN_CANDIDATES_DIR}"/*)

			for candidate_path in "${candidate_paths[@]}"; do
				candidates+=("${candidate_path##*/}")
			done
			;;
		install|i|list|ls)
			candidates=${SDKMAN_CANDIDATES[@]}
			;;
		env|e)
			candidates=("init" "install" "clear")
			;;
		offline)
			candidates=("enable" "disable")
			;;
		selfupdate)
			candidates=("force")
			;;
		flush)
			candidates=("temp" "version")
			;;
	esac

	COMPREPLY=($(compgen -W "${candidates[*]}" -- "$current_word"))
}

__sdkman_complete_candidate_version() {
	local -r command=$1
	local -r candidate=$2
	local -r candidate_version=$3

	local -a candidates

	case $command in
		default|d|home|h|uninstall|rm|use|u)
			local -r version_paths=("${SDKMAN_CANDIDATES_DIR}/${candidate}"/*)

			for version_path in "${version_paths[@]}"; do
				[[ $version_path = *current ]] && continue

				candidates+=("${version_path##*/}")
			done
			;;
		install|i)
			while IFS= read -r -d, version || [[ -n "$version" ]]; do
				candidates+=("$version")
			done <<< "$(curl --silent "${SDKMAN_CANDIDATES_API}/candidates/$candidate/${SDKMAN_PLATFORM}/versions/all")"
			;;
	esac

	COMPREPLY=($(compgen -W "${candidates[*]}" -- "$candidate_version"))
}

complete -o default -F _sdk sdk

# Set 'sdkman_auto_complete' to 'true' in .sdkman/etc/config to enable completion

